<!--
 * @Author: chengjiang
 * @Date: 2024-11-12 14:52:36
 * @Description: 
-->
<template>
  <a-button class="editable-add-btn mb-2 float-right" @click="refresh">
    <RedoOutlined />
  </a-button>
  <a-table bordered :data-source="dataSource" :columns="columns">
    <template #bodyCell="{ column, text, record }">
      <template v-if="['code'].includes(column.dataIndex)">
        <div>
          {{ text }}
        </div>
      </template>
      <template v-if="['name'].includes(column.dataIndex)">
        <div>
          <a-input v-if="editableData[record.key]" v-model:value="editableData[record.key][column.dataIndex]"
            style="margin: -5px 0" />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-if="column.dataIndex === 'recycle'">
        <a-row v-if="editableData[record.key]">
          <a-col :span="12">
            <a-slider v-model:value="editableData[record.key]['recycle']" :min="-25" :max="25" :step="0.1" />
          </a-col>
          <a-col :span="4">
            <a-input-number v-model:value="editableData[record.key]['recycle']" :min="-25" :max="25" :step="1" style="margin-left: 16px" />
          </a-col>
        </a-row>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template v-else-if="column.dataIndex === 'sell'">
        <a-row v-if="editableData[record.key]">
          <a-col :span="12">
            <a-slider v-model:value="editableData[record.key]['sell']" :min="-25" :max="25" :step="0.1" />
          </a-col>
          <a-col :span="4">
            <a-input-number v-model:value="editableData[record.key]['sell']" :min="-25" :max="25" :step="1" style="margin-left: 16px" />
          </a-col>
        </a-row>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a-typography-link class="mr-2" @click="save(record.key)">保存</a-typography-link>
            <a-popconfirm title="确认取消吗？" @confirm="cancel(record.key)">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.key)">编辑</a>
          </span>
          <!-- <a-popconfirm class="mr-2 ml-2" v-if="dataSource.length" title="确认删除吗?" @confirm="onDelete(record.key)">
          </a-popconfirm> -->
          <a-button class="mr-2 ml-2" disabled>删除</a-button>
          <!-- <a-popconfirm v-if="dataSource.length" title="确认重置吗?" @confirm="reload(record.key)">
            <a>重置</a>
          </a-popconfirm> -->
        </div>
      </template>
    </template>
  </a-table>
  <a-button type="dashed" class="editable-add-btn mt-2 mb-5 pr-20 pl-20" @click="handleAdd">
    <PlusOutlined />
  </a-button>
</template>

<script lang="ts" setup>
import { RedoOutlined } from '@ant-design/icons-vue';
import { reactive, ref } from 'vue';
import type { Ref, UnwrapRef } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
import { ListGoldSetting, UpdateGoldSetting } from '../../../api/home';
import { message } from 'ant-design-vue';
const prp = defineProps<{
  pageType: number // 0: 看价盘，1: customer临售盘
}>()
interface DataItem {
  key: number;
  code: string;
  name: string;
  recycle: number;
  sell: number;
}
const columns = [
  {
    title: 'Code',
    dataIndex: 'code',
    // width: '30%',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '调整回收价',
    dataIndex: 'recycle',
  },
  {
    title: '调整销售价',
    dataIndex: 'sell',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];

// 获取数据列表：initFunc
const key = 'getList';
message.loading({ content: '加载数据...', key });
let dataSource: Ref<DataItem[]> = ref([]);
const initFunc = async () => {
  dataSource.value = []
  const listRet = ListGoldSetting({ priceType: prp.pageType })
  listRet.then((res) => {
    const lst = res.data
    for (const val of lst) {
      dataSource.value.push({
        key: val.id,
        code: val.currencyCode,
        name: val.currencyName,
        recycle: val.recyclePrice / 100,
        sell: val.sellPrice / 100
      })
    }
    message.success({ content: '获取成功!', key, duration: 2 });
  }).catch(() => {
    message.error({ content: '获取数据失败!', key, duration: 2 });
  })
};
initFunc();

// 刷新方法：
const refresh = () => {
  message.loading({ content: '加载数据...', key });
  // sleep 2s
  setTimeout(() => { }, 2000);
  message.success({ content: '获取成功!', key, duration: 2 });
  initFunc();
}

const editableData: UnwrapRef<Record<string, any>> = reactive({});

const edit = (key: number) => {
  editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = (key: number) => {
  Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
  console.log('编辑后的：', editableData[key])
  UpdateGoldSetting(key, {
    id: editableData[key].key,
    priceType: prp.pageType, // 0: 看价盘，1: customer临售盘
    currencyCode: editableData[key].code, // 币种英文代码
    currencyName: editableData[key].name, // 币种中文名称
    recyclePrice: editableData[key].recycle * 100, // 回收价
    sellPrice: editableData[key].sell * 100, // 销售价
  }).then(() => {
    message.success('保存成功')
  }).catch(() => {
    message.error('保存失败')
  })
  delete editableData[key];
};
const cancel = (key: string) => {
  delete editableData[key];
};

console.log(edit, save, cancel)

// const onDelete = (key: number) => {
//   dataSource.value = dataSource.value.filter(item => item.key !== key);
// };
// const reload = (key: string) => {
//   // key 转化为number
//   const key1 = parseInt(key)
//   Object.assign(dataSource.value.filter(item => key1 === item.key)[0], editableData[key1]);
//   UpdateGoldSetting(key1, {
//     id: editableData[key1].key,
//     priceType: prp.pageType, // 0: 看价盘，1: customer临售盘
//     currencyCode: editableData[key].code, // 币种英文代码
//     currencyName: editableData[key].name, // 币种中文名称
//     recyclePrice: 0, // 回收价
//     sellPrice: 0, // 销售价
//   }).then(() => {
//     message.success('保存成功')
//   }).catch(() => {
//     message.error('保存失败')
//   })
//   delete editableData[key];
// };
const handleAdd = () => {
  dataSource.value.push({
    key: 0,
    code: '',
    name: '',
    recycle: 0,
    sell: 0
  });
};
// 触发添加接口。
</script>

<style lang="less">
.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>